<template>
  <Page :title="navTitle">
    <template #navBarCustom>
      <div class=""></div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div class="container w-full h-full p-20px box-border bg-white flex flex-col" v-if="inited">
          <el-table :data="tableData" style="width: 100%; height: 100%" height="100%" stripe>
            <el-table-column
              v-for="(column, index) in tableColumn"
              :key="index"
              :fixed="column.fixed"
              :align="column.align"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
            >
              <template slot-scope="scope">
                <div
                  class="input flex-center"
                  @click="changeSubmitStatus(scope.row)"
                  v-if="column.prop === 'submitStatus'"
                >
                  <img
                    class="right"
                    src="static/icons/input-disabled.png"
                    v-show="scope.row[column.prop] === 2"
                  />
                  <img
                    class="right"
                    src="static/icons/input-right.png"
                    v-show="scope.row[column.prop] === 1"
                  />
                  <img
                    class="error"
                    src="static/icons/input-error.png"
                    v-show="scope.row[column.prop] === 0"
                  />
                </div>
                <div v-else>{{ scope.row[column.prop] }}</div>
              </template>
              <el-table-column
                v-for="(child_column, child_index) in column.children"
                :key="child_index"
                :align="column.align"
                :prop="child_column.prop"
                :label="child_column.label"
                :width="child_column.width"
              >
                <template slot-scope="scope">
                  <div
                    class="input flex-center"
                    @click="changeTableData(scope.row, child_column.prop)"
                  >
                    <img
                      class="right"
                      src="static/icons/input-right.png"
                      v-show="
                        scope.row['submitStatus'] != 0 &&
                        scope.row[child_column.prop]['studentScore'] === 1
                      "
                    />
                    <img
                      class="error"
                      src="static/icons/input-error.png"
                      v-show="
                        scope.row['submitStatus'] != 0 &&
                        scope.row[child_column.prop]['studentScore'] === 0
                      "
                    />
                    <span v-show="scope.row['submitStatus'] === 0">-</span>
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
          <div class="footer flex justify-center pt-30px pb-10px">
            <CustomButton class="submit" style="width: 4.53rem" @click="submit">提交</CustomButton>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import CustomButton from '@/components/button'
import { mapState } from 'vuex'
import { getExamStudentQuestions, upExamQuestionScoreListApi } from '@/api/homework-input'

export default {
  components: {
    Page,
    CustomButton
  },
  data() {
    return {
      inited: false,
      tableColumn: [],
      tableData: []
    }
  },
  computed: {
    ...mapState(['app', 'homework']),
    hasShownStartPopup() {
      const { homeworkInput_hasShownStartPopup = false } = this.app.status

      return homeworkInput_hasShownStartPopup
    },
    currentHomework() {
      return this.homework.currentHomework
    },
    record() {
      return this.currentHomework.record
    },
    students() {
      const {
        record: { examStudentDOS }
      } = this.currentHomework

      return examStudentDOS
    },
    questions() {
      const { questions } = this.currentHomework
      return questions
    },
    navTitle() {
      const {
        record: { examName }
      } = this.currentHomework

      return `录入成绩（${examName}）`
    }
  },
  created() {
    this.init()
  },
  mounted() {
    if (!this.hasShownStartPopup) {
      this.$popup.show({
        type: 'alert',
        success: (popup) => {
          popup.$on('confirm', () => {
            this.$popup.hide('alert')
          })
          popup.setData({
            content: '点击某个格子可以切换√或x'
          })
        }
      })
      this.$store.commit('setAppStatus', { key: 'homeworkInput_hasShownStartPopup', value: true })
    }
  },
  methods: {
    async init() {
      const {
        record: { id: examId, subject: subjectId },
        questions
      } = this

      const { success, data } = await this.$storage.homework_input.getSubjectSettingsItem(subjectId)

      let students = []
      let studentScore = 1
      if (success) {
        const {
          inputer: { checkedList },
          correcter: { value }
        } = data

        students = this.students
        if (Array.isArray(checkedList) && checkedList.length > 0) {
          students = checkedList
            .map((student_checked) => {
              const [type, typeId, studentId] = student_checked.id.split('-')
              const student = this.students.find((s) => s.studentId === studentId)
              if (student) {
                return student
              } else {
                return null
              }
            })
            .filter((student) => !!student)
        } else {
          students = this.students
        }
        studentScore = parseInt(value)
      } else {
        students = this.students
      }

      if (
        !Array.isArray(students) ||
        students.length === 0 ||
        !Array.isArray(questions) ||
        questions.length === 0
      ) {
        return
      }

      const genTableColumn = (questions) => {
        const pageGroups = questions.reduce((groups, question) => {
          const key = question.pageIndex

          if (!groups[key]) {
            groups[key] = []
          }

          groups[key].push(question)

          return groups
        }, {})

        let count = 0
        const column_pages = []
        for (let pageIndex in pageGroups) {
          const child_questions = pageGroups[pageIndex]
          column_pages.push({
            align: 'center',
            prop: '',
            label: pageIndex != 'undefined' ? `第${pageIndex}页` : '无页码',
            width: '',
            children: child_questions.map((question) => {
              const { questionIndex } = question

              return {
                align: 'center',
                prop: `question_${count++}`,
                label: questionIndex ? `${questionIndex}` : '无题号',
                width: '',
                children: []
              }
            })
          })
        }

        return [
          {
            fixed: true,
            align: 'center',
            prop: 'name',
            label: '姓名',
            width: '',
            children: []
          },
          {
            fixed: true,
            align: 'center',
            prop: 'submitStatus',
            label: '是否提交',
            width: 100,
            children: []
          }
        ].concat(column_pages)
      }

      const genTableData = (students, questions) => {
        const questionData = {}
        questions.forEach((question, index) => {
          const { questionId } = question
          questionData[`question_${index}`] = {
            questionId,
            studentScore
          }
        })

        const deepCopy = (obj) => JSON.parse(JSON.stringify(obj))

        return Promise.all(
          students.map(async (s) => {
            const { data: studentResultList } = await getExamStudentQuestions({
              examId,
              studentId: s.studentId
            })
            const obj = deepCopy(questionData)
            const { notSubmitStudentIds = [] } = data ? data : {}
            let submitStatus = notSubmitStudentIds.includes(s.studentId) ? 0 : 1
            for (let key in obj) {
              const { questionId } = obj[key]
              const studentResult = studentResultList.find((i) => {
                return i.questionId === questionId
              })
              if (studentResult) {
                try {
                  const { studentAnswer, studentAnswerUrl, studentScore } = studentResult

                  if (studentAnswer || studentAnswerUrl) {
                    // 在平板上提交了作业
                    submitStatus = 2
                  }

                  if (studentScore != null || studentScore != undefined) {
                    obj[key].studentScore = parseInt(studentScore)
                  }
                } catch (error) {}
              }
            }

            return {
              name: s.studentName,
              submitStatus, // 0 => 不提交 1 => 未提交，即将提交 2 => 已经提交
              studentId: s.studentId,
              ...obj
            }
          })
        )
      }

      this.tableColumn = genTableColumn(questions)
      this.tableData = await genTableData(students, questions)
      this.inited = true
      this.$nextTick(() => {
        if (!Array.prototype.flatMap) {
          document.querySelector('.el-table--border').style.cssText +=
            'border: 0.0169rem solid #ebeef5;border-bottom: 0.0168rem solid #ebeef5;'
        }
      })
    },
    changeTableData(data, key) {
      // 如果选了不提交
      if (data.submitStatus === 0) return

      if (data[key]['studentScore']) {
        data[key]['studentScore'] = 0
      } else {
        data[key]['studentScore'] = 1
      }
    },
    changeSubmitStatus(data) {
      if (!data || (data && data.submitStatus === 'undefined')) return

      const { submitStatus } = data
      // 已经提交过这次作业
      if (submitStatus === 2) return

      data.submitStatus = submitStatus === 0 ? 1 : 0
    },
    // 更新成绩录入设置
    updateSetting() {
      const notSubmitStudentIds = this.tableData
        .map((item) => {
          const { submitStatus, studentId } = item

          if (submitStatus === 0) {
            return studentId
          } else {
            return null
          }
        })
        .filter((item) => item)

      const {
        record: { subject: subjectId }
      } = this
      this.$storage.homework_input.getSubjectSettingsItem(subjectId).then(({ success, data }) => {
        if (success) {
          this.$storage.homework_input.putSubjectSettingsItem({
            subjectId,
            value: Object.assign(data, { notSubmitStudentIds })
          })
        } else {
          this.$storage.homework_input.setSubjectSettingsItem({
            subjectId,
            value: {
              inputer: {
                checkedList: []
              },
              correcter: {
                value: '1'
              },
              notSubmitStudentIds
            }
          })
        }
      })
    },
    async submit() {
      const {
        record: { id: examId }
      } = this.currentHomework

      const data = {
        examSubmitScoreList: this.tableData
          .map((item) => {
            const { submitStatus, studentId } = item

            if (submitStatus === 0) return null

            const questions = []
            for (let key in item) {
              if (key.indexOf('question_') != -1) {
                questions.push(item[key])
              }
            }

            return questions.map((question, index) => {
              const { questionId, studentScore } = question

              return {
                examId,
                questionId,
                studentId,
                studentScore,
                completeFlag: index === questions.length - 1 ? 1 : 0
              }
            })
          })
          .filter((item) => item)
          .flat(Infinity)
      }

      if (data.examSubmitScoreList.length === 0) {
        this.$popup.show({
          type: 'alert',
          success: (popup) => {
            popup.$on('confirm', () => {
              this.$popup.hide('alert')
            })
            popup.setData({
              content: '请选择至少一个学生提交'
            })
          }
        })

        return
      }

      const loading = this.$loading({
        lock: true,
        text: '正在提交...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内上传不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)
      const { data: success, msg } = await upExamQuestionScoreListApi(data)
      clearTimeout(timer)
      loading.close()

      if (success) {
        this.updateSetting()
        this.$message.success('提交成功')
        this.$route.params.completed = true
        this.$router.back()
      } else {
        this.$message.error('提交失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 16px;

  .input {
    .right {
      width: 49.2px;
      height: 35px;
    }

    .error {
      width: 35px;
      height: 35px;
    }
  }
}

/deep/ .el-table {
  thead.is-group th.el-table__cell {
    background: #fff;
  }
}

/deep/ .el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background: rgba($color: #edf9ff, $alpha: 0.5);
}

/deep/ .el-table__row.hover-row .el-table__cell {
  background: rgba($color: #edf9ff, $alpha: 1) !important;
}

/deep/ table tr > th {
  font-size: 16px !important;
}

/deep/ table tr:first-child > th:first-child {
  font-size: 20px !important;
}

/deep/ table tr > td:first-child {
  font-size: 20px !important;
}
</style>
